#include<iostream>
#include<wait.h>
#include<string.h>
#include<sys/types.h>
using namespace std;

void reader(int rfd)
{
    char buffer[1024];
    while(1)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer)-1);
        (void)n;
        printf("father get a message: %s", buffer);
    }
}

void wirter(int wfd)
{
    const char* str="hello father,Im child";
    char buffer[124];
    pid_t id=getpid();
    int cnt=0;
    while(1)
    {
        snprintf(buffer,sizeof(buffer),"message: %s, pid: %d, count: %d\n",str,id,cnt);
        write(wfd,buffer,strlen(buffer));
        cnt++;
        sleep(1);
    }
}

int main()
{
    cout<<"PIPE_BUF:"<<_PC_PIPE_BUF<<endl;
    int pipefd[2];
    int n=pipe(pipefd);
    if(n<0) return 1;
    cout<<"pipefd[0]: "<<pipefd[0]<<"pipefd[1]: "<<pipefd[1]<<endl;
    pid_t id=fork();
    if(id==0)
    {
        //子进程 
        close(pipefd[0]);//关闭读入端

        wirter(pipefd[1]);

        exit(0);
    }

    close(pipefd[1]);
    reader(pipefd[0]);
    wait(NULL);
    return 0;
}